package com.jilefojing.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.octo.captcha.service.multitype.MultiTypeCaptchaService;

@Controller
@RequestMapping("/validata")
public class JcaptchaImageWeb {
	public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private MultiTypeCaptchaService captchaService;

	@RequestMapping("img")
	public void handleRequest(HttpServletRequest request, HttpServletResponse response) {
		ServletOutputStream responseOutputStream = null;
		try {
			byte[] captchaChallengeAsJpeg = null;
			ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
			String captchaId = request.getSession().getId();
			BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());

			ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);

			captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

			// flush it in the response
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);

			responseOutputStream = response.getOutputStream();
			responseOutputStream.write(captchaChallengeAsJpeg);
			responseOutputStream.flush();
		} catch (Exception e) {
			logger.error("generate captcha image error: {}", e.getMessage());
		} finally {
			if (responseOutputStream != null) {
				try {
					responseOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

		// try {
		// ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		// String captchaId = request.getSession().getId();
		// BufferedImage challenge =
		// imageCaptchaService.getImageChallengeForID(captchaId,
		// request.getLocale());
		//
		// response.setHeader("Cache-Control", "no-store");
		// response.setHeader("Pragma", "no-cache");
		// response.setDateHeader("Expires", 0L);
		// response.setContentType("image/jpeg");
		//
		// ImageIO.write(challenge, "jpeg", jpegOutputStream);
		// byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		//
		// ServletOutputStream respOs = response.getOutputStream();
		// respOs.write(captchaChallengeAsJpeg);
		// respOs.flush();
		// respOs.close();
		// } catch (IOException e) {
		// logger.error("generate captcha image error: {}", e.getMessage());
		// }
	}

}